﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace XFControls.Utils
{
    public class XFImageCache : IDisposable
    {
        private int _maxFiles = 50;
        private Dictionary<string, MemoryStreamWrapper> _memoryStreams = new Dictionary<string, MemoryStreamWrapper>();

        public void Add(byte[] imageFile, string Uri)
        {
            return;
            lock (this)
            {
                if (_memoryStreams.Count > _maxFiles)
                {
                    var rem = _memoryStreams.OrderBy(m => m.Value.LastUsed).First();
                    _memoryStreams.Remove(rem.Key);
                }
                if (!_memoryStreams.ContainsKey(Uri))
                    _memoryStreams.Add(Uri, new MemoryStreamWrapper(imageFile));
            }
        }

        public byte[] this[string Uri]
        {
            get
            {

                return null;
                lock (this)
                {
                    if (_memoryStreams.ContainsKey(Uri))
                        return _memoryStreams[Uri].Stream;
                }

                string key = "";
                if (string.IsNullOrEmpty(key = XFGraphics.ImageCache.FirstOrDefault(k => k.Key.StartsWith(Uri)).Key)) return null;

                try
                {
                    var fs = new FileStream(XFGraphics.ImageCache[key], FileMode.Open);
                    var array = new byte[fs.Length];

                    fs.Read(array, 0, (int)fs.Length);

                    Add(array, Uri);
                    return array;
                }
                catch (IOException) { }

                return null;
            }
        }

        #region IDisposable Members

        public void Dispose() { }

        #endregion
    }

    public class MemoryStreamWrapper
    {
        public byte[] Stream
        {
            get
            {
                LastUsed = DateTime.Now;
                return _stream;
            }
        }
        public DateTime LastUsed { get; private set; }

        private byte[] _stream;

        public MemoryStreamWrapper(byte[] stream)
        {
            _stream = stream;
        }
    }
}
